package com.yellowpage.omc.datacollect.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.struts2.ServletActionContext;

import com.yellowpage.omc.datacollect.data.DataCollect;
import com.yellowpage.omc.datacollect.data.DataCollectBatch;
import com.yellowpage.omc.datacollect.service.DataCollectBatchService;
import com.yellowpage.omc.datacollect.service.DataCollectImportTask;
import com.yellowpage.omc.datacollect.service.DataCollectService;
import com.yellowpage.white.common.Configuration;
import com.yellowpage.white.struts.BaseAction;

public class DataCollectBatchAction extends BaseAction {
	
	private static final int BUFFER_SIZE = 16 * 1024;
	private String uploadFileName;
	private String uploadContentType;  
	private String savePath;

	public String RESULT_QUERY = "query";
	public String RESULT_ADD = "add";
	public String RESULT_EDIT = "edit";
	public String RESULT_IMPORT = "importData";

	private Configuration configuration;

	public void setConfiguration(Configuration configuration) {
		this.configuration = configuration;
	}

	private List<DataCollectBatch> dataCollectBatchList = new ArrayList<DataCollectBatch>();
	private List<Map> resultList = new ArrayList<Map>();

	private DataCollectBatch dataCollectBatch;
	private DataCollectBatchService dataCollectBatchService;
	private DataCollectService dataCollectService;
	
	private String selectedId;
	private String[] selectedIds;
	private String message;

	private String query_dataCollectBatchId;
	private String query_batchNum;
	private String query_dataCount;
	private String query_importCount;
	private String query_createUser;
	private String query_createTime;
	private String query_lastUpdateTime;
	private String query_source;
	private String query_status;

	private File upload;	
	
	private Map dataSourceMap = new HashMap();
	private Map batchStatusMap = new HashMap();

	// private List<DataCollect> dataCollectList = new ArrayList<DataCollect>();

	public void prepare() {
		super.prepare();
		
		dataSourceMap = dataCollectBatchService.getDataSourceMap();
		batchStatusMap = dataCollectBatchService.getBatchStatusMap();

		if (this.selectedId != null && !this.selectedId.equals("")) {
			this.dataCollectBatch = dataCollectBatchService
					.getDataCollectBatch(Long.parseLong(selectedId));
		}
	}

	public String queryByPage() {
		initPageRender();

		Map queryMap = new HashMap();
		queryMap.put("dataCollectBatchId", query_dataCollectBatchId);
		queryMap.put("batchNum", query_batchNum);
		queryMap.put("dataCount", query_dataCount);
		queryMap.put("importCount", query_importCount);
		queryMap.put("createUser", query_createUser);
		queryMap.put("createTime", query_createTime);
		queryMap.put("lastUpdateTime", query_lastUpdateTime);
		queryMap.put("source", query_source);
		queryMap.put("status", query_status);

		resultList = dataCollectBatchService.queryDataCollectBatchByPage(
				queryMap, pageRender);

		setPageRenderToRequest();

		return RESULT_QUERY;
	}

	public String toImportDataCollect() {
		return RESULT_IMPORT;
	}
	
	
	private static void copy(File src, File dst) {  
        InputStream in = null;  
        OutputStream out = null;  
        try {  
            in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);  
            out = new BufferedOutputStream(new FileOutputStream(dst),  
                    BUFFER_SIZE);  
            byte[] buffer = new byte[BUFFER_SIZE];  
            int len = 0;  
            while ((len = in.read(buffer)) > 0) {  
                out.write(buffer, 0, len);  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            if (null != in) {  
                try {  
                    in.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
            if (null != out) {  
                try {  
                    out.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
        }  
    }  
	
	

	public String importDataCollect() {
		
		 //根据服务器的文件保存地址和原文件名创建目录文件全路径  
        String dstPath = ServletActionContext.getServletContext()  
                                .getRealPath(this.getSavePath())  
                                + "\\" + this.upload.getName();  
         
        System.out.println("上传的文件的类型："+ this.getUploadContentType());  
         
        File dstFile = new File(dstPath);  
        copy(this.upload, dstFile);  
				
		Workbook workbook =  null;
		int sheetCount = 0;
		
		List<DataCollect> dataCollectList = null;
		
		SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");  
		SimpleDateFormat fmtBatchNum = new SimpleDateFormat("yyyyMMdd");  
		
		String batchNumDate = fmtBatchNum.format(new Date());
		
		String seq = "";  
		String name = "";   
		String link = "";  
		String icon = "";  
		String telType = "";    
		String tel = "";  
		String city = "";  
		String class01 = "";   
		String class02 = "";  
		String addr = "";   
		String info = "";  
		String tel2 = "";  
		
		long dataCount = 0;
		int currentRow = 0;
		int currentCol = 0;

		try {

			if (dstFile == null || dstFile.length() == 0)
				this.addActionError("** 文件 不能为空 !");

			dataCollectBatch.setFileName(dstFile.getName());

			dataCollectBatch.setBatchNum(batchNumDate);
			dataCollectBatch.setCreateTime(new Date());
			dataCollectBatch.setCreateUser(loginUser.getUserId());
			dataCollectBatch.setLastUpdateTime(new Date());
			dataCollectBatch.setStatus("IMPORTING");

			dataCollectBatchService.saveDataCollectBatch(dataCollectBatch);
			
			dataCollectList = new ArrayList<DataCollect>();	

			if (!this.hasActionErrors()) {

				try {
					
					FileInputStream is = new FileInputStream(dstFile); //文件流  
			        workbook = WorkbookFactory.create(is); //这种方式 Excel 2003/2007/2010 都是可以处理的  
			        sheetCount = workbook.getNumberOfSheets();  //Sheet的数量  
					
				} catch (Exception e) {
					this.addActionError("** 导入文件非Microsoft Excel格式 ! ");
				}
				if (workbook != null) {		
					
							//遍历每个Sheet  
					        for (int s = 0; s < sheetCount; s++) {  
					            Sheet sheet = workbook.getSheetAt(s);  
					            int rowCount = sheet.getPhysicalNumberOfRows(); //获取总行数  
					            
					            dataCollectBatch.setDataCount(dataCount + rowCount);
					            
					            //遍历每一行  
					            for (int r = 1; r < rowCount; r++) {  
					            	currentRow = r;
					            	
					                Row row = sheet.getRow(r);  
					                int cellCount = row.getPhysicalNumberOfCells(); //获取总列数  
					                
					                //遍历每一列  					                
					                seq = row.getCell(0).getStringCellValue();  
									name = row.getCell(1).getStringCellValue();  
									link = row.getCell(2).getStringCellValue();  
									icon = row.getCell(3).getStringCellValue();  
									telType = row.getCell(4).getStringCellValue();  
									tel = row.getCell(5).getStringCellValue();  
									city = row.getCell(6).getStringCellValue();  
									class01 = row.getCell(7).getStringCellValue();  
									class02 = row.getCell(8).getStringCellValue();  
									addr = row.getCell(9).getStringCellValue();  
									info = row.getCell(10).getStringCellValue();  
									tel2 = row.getCell(11).getStringCellValue();
									
									DataCollect dataCollect = new DataCollect();

									dataCollect.setDataCollectBatchId(dataCollectBatch.getDataCollectBatchId());

									dataCollect.setSeq(Long.parseLong(seq));
									dataCollect.setName(name);
									dataCollect.setLink(link);
									dataCollect.setIcon(icon);
									dataCollect.setTelType(telType);
									dataCollect.setTel(tel);
									dataCollect.setCity(city);
									dataCollect.setClass01(class01);
									dataCollect.setClass02(class02);
									dataCollect.setAddr(addr);
									dataCollect.setInfo(info);
									dataCollect.setTel02(tel2);
									dataCollect.setCreateTime(new Date());
									
									dataCollect.setStatus("PENDING");									
									
									dataCollectList.add(dataCollect);
									
									//dataCollectService.saveDataCollect(dataCollect);
		               
					                
					                
					            }  
					        }  
					
				}
			}
		} catch (Exception e) {
			this.addActionError("** 解析文件出错 ! currentRow:" + currentRow + " Seq:" + seq + " Error::" + e.getMessage());
			e.printStackTrace();
		} 
		
		dataCollectBatch.setDataCount(new Long((long)dataCollectList.size()));
		dataCollectBatchService.updateDataCollectBatch(dataCollectBatch);

		
		if(dataCollectList.size() > 0){
			DataCollectImportTask dataCollectImportTask = new DataCollectImportTask(dataCollectList,dataCollectBatch, dataCollectBatchService, dataCollectService);
			
			dataCollectImportTask.run();
		

			//DataCollect dataCollect = null;
			
			//dataCollectBatchService.importDataCollect(dataCollectList);

//			try {
//				
//				for (int s = 0; s < dataCollectList.size(); s++) {
//					dataCollect = (DataCollect) dataCollectList.get(s);
//					
//					dataCollectService.initDataCollectRegion(dataCollect);						
//									
//					List saveDataCollectList = dataCollectBatchService.processImportDataCollect(dataCollect);
//					
//					for(int i = 0; i < saveDataCollectList.size(); i++){
//						dataCollectService.saveDataCollect((DataCollect)saveDataCollectList.get(i));
//					}				
//					
//				}
//
//				dataCollectBatch.setStatus("COMPLETED");
//				dataCollectBatchService.updateDataCollectBatch(dataCollectBatch);
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
			
			dataCollectBatch.setStatus("COMPLETED");
     		dataCollectBatchService.updateDataCollectBatch(dataCollectBatch);

		}
			
	
		
		

		if (this.hasActionErrors())
			return RESULT_IMPORT;
		else {
			
			this.addActionMessage("导入启动成功.....");
			return queryByPage();
			
//			try {
//				dataCollectBatchService.importDataCollect(dataCollectList);
//				
//			} catch (Exception e) {
//				log.error(e.getMessage(), e);
//				this.addActionError("** 导入启动失败!");
//				return RESULT_IMPORT;
//			}
		}

	}

	public String toAdd() {
		return RESULT_ADD;
	}

	public String save() {

		dataCollectBatchService.saveDataCollectBatch(dataCollectBatch);

		message = "新增成功!";
		return RESULT_ADD;
	}

	public void validateSave() {
		if (dataCollectBatch.getBatchNum().length() == 0) {
			this.addActionError("** BatchNum 不能为空 !");
		}
		if (dataCollectBatch.getSource().length() == 0) {
			this.addActionError("** Source 不能为空 !");
		}
		if (dataCollectBatch.getStatus().length() == 0) {
			this.addActionError("** Status 不能为空 !");
		}

		this.setValidatorResult("/omc/datacollect/DataCollectBatchAdd.jsp");
	}

	public String toEdit() {
		Long id = new Long(selectedId);

		dataCollectBatch = dataCollectBatchService.getDataCollectBatch(id);

		return RESULT_EDIT;
	}

	public String update() {

		dataCollectBatchService.updateDataCollectBatch(dataCollectBatch);

		message = "修改成功!";

		return RESULT_EDIT;
	}

	public void validateUpdate() {
		if (dataCollectBatch.getBatchNum().length() == 0) {
			this.addActionError("** BatchNum 不能为空 !");
		}
		if (dataCollectBatch.getSource().length() == 0) {
			this.addActionError("** Source 不能为空 !");
		}
		if (dataCollectBatch.getStatus().length() == 0) {
			this.addActionError("** Status 不能为空 !");
		}
		this.setValidatorResult("/omc/datacollect/DataCollectBatchUpdate.jsp");
	}

	public String delete() {
		List ids = new ArrayList();

		for (String id : selectedIds) {
			ids.add(Long.valueOf(id));
		}

		try {
			this.dataCollectBatchService.delete(ids);
		} catch (Exception e) {
			System.out.println("异常....");
			this.addActionError("** 可能含有子记录约束冲�?删除失败 !");
		}

		return queryByPage();
	}

	/**
	 * getters and setters
	 * 
	 * @return
	 */
	public void setDataCollectBatch(DataCollectBatch dataCollectBatch) {
		this.dataCollectBatch = dataCollectBatch;
	}

	public DataCollectBatch getDataCollectBatch() {
		return dataCollectBatch;
	}

	public void setDataCollectBatchService(
			DataCollectBatchService dataCollectBatchService) {
		this.dataCollectBatchService = dataCollectBatchService;
	}

	public List<DataCollectBatch> getDataCollectBatchList() {
		return dataCollectBatchList;
	}

	public void setDataCollectBatchList(
			List<DataCollectBatch> dataCollectBatchList) {
		this.dataCollectBatchList = dataCollectBatchList;
	}

	public String getSelectedId() {
		return selectedId;
	}

	public void setSelectedId(String selectedId) {
		this.selectedId = selectedId;
	}

	public String[] getSelectedIds() {
		return selectedIds;
	}

	public void setSelectedIds(String[] selectedIds) {
		this.selectedIds = selectedIds;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public List<Map> getResultList() {
		return resultList;
	}

	public void setResultList(List<Map> resultList) {
		this.resultList = resultList;
	}

	public String getQuery_dataCollectBatchId() {
		return this.query_dataCollectBatchId;
	}

	public void setQuery_dataCollectBatchId(String dataCollectBatchId) {
		this.query_dataCollectBatchId = dataCollectBatchId;
	}

	public String getQuery_batchNum() {
		return this.query_batchNum;
	}

	public void setQuery_batchNum(String batchNum) {
		this.query_batchNum = batchNum;
	}

	public String getQuery_dataCount() {
		return this.query_dataCount;
	}

	public void setQuery_dataCount(String dataCount) {
		this.query_dataCount = dataCount;
	}

	public String getQuery_importCount() {
		return this.query_importCount;
	}

	public void setQuery_importCount(String importCount) {
		this.query_importCount = importCount;
	}

	public String getQuery_createUser() {
		return this.query_createUser;
	}

	public void setQuery_createUser(String createUser) {
		this.query_createUser = createUser;
	}

	public String getQuery_createTime() {
		return this.query_createTime;
	}

	public void setQuery_createTime(String createTime) {
		this.query_createTime = createTime;
	}

	public String getQuery_lastUpdateTime() {
		return this.query_lastUpdateTime;
	}

	public void setQuery_lastUpdateTime(String lastUpdateTime) {
		this.query_lastUpdateTime = lastUpdateTime;
	}

	public String getQuery_source() {
		return this.query_source;
	}

	public void setQuery_source(String source) {
		this.query_source = source;
	}

	public String getQuery_status() {
		return this.query_status;
	}

	public void setQuery_status(String status) {
		this.query_status = status;
	}

	

	public void setDataCollectService(DataCollectService dataCollectService) {
		this.dataCollectService = dataCollectService;
	}

	public Map getDataSourceMap() {
		return dataSourceMap;
	}

	public void setDataSourceMap(Map dataSourceMap) {
		this.dataSourceMap = dataSourceMap;
	}

	public Map getBatchStatusMap() {
		return batchStatusMap;
	}

	public void setBatchStatusMap(Map batchStatusMap) {
		this.batchStatusMap = batchStatusMap;
	}

	public String getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public String getSavePath() {
		return savePath;
	}

	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}

	public String getUploadContentType() {
		return uploadContentType;
	}

	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

}
